# encoding: utf-8 
from PyQt4.QtCore import pyqtSignature, QUrl
from PyQt4.QtGui import QDialog, QApplication
from PyQt4.QtNetwork import QNetworkCookieJar
import cookielib, urllib2
from Ui_login import Ui_Dialog

class login(QDialog, Ui_Dialog):
    def __init__(self, parent=None,status=None,loginUrl=None, successUrl=None, goodUrl=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.parent=parent
        self.loginUrl=loginUrl
        self.successUrl=successUrl
        self.goodUrl=goodUrl
        self.status=status
        
        self.cookieJar = QNetworkCookieJar()
        self.webView.page().networkAccessManager().setCookieJar(self.cookieJar)
        self.webView.load(QUrl(self.loginUrl))
        #self.webView.settings().setIniCodec('UTF-8')
    
    @pyqtSignature("bool")
    def on_webView_loadFinished(self, p0):
        currentUrl =str(self.webView.url().toString())
        if self.successUrl in currentUrl:
            self.webView.load(QUrl(self.goodUrl))
            newJar = self.getNewCookieJar()
            opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(newJar))
            self.parent.opener=opener
            self.saveCookie(self.cookieJar)
            self.status.setText('Success')
            self.close()
            
    #根据webview的cookie构建模拟提交的cookie
    def getNewCookieJar(self):
        newJar = cookielib.CookieJar()
        for cookie in self.cookieJar.allCookies():
            newJar.set_cookie(self.make_cookie(str(cookie.name()), str(cookie.value()),str(cookie.path().toUtf8()),str(cookie.domain().toUtf8())))
        return newJar
    def saveCookie(self,netCookieJar):
        fileJar =cookielib.MozillaCookieJar('cookie.txt')
        for cookie in netCookieJar.allCookies():
            fileJar.set_cookie(self.make_cookie(str(cookie.name()), str(cookie.value()),str(cookie.path().toUtf8()),str(cookie.domain().toUtf8())))
        fileJar.save(ignore_discard=True,ignore_expires=True)
    def make_cookie(self,name,value,path,domain):
        return cookielib.Cookie(
            version=0,
            name=name,
            value=value,
            port=None,
            port_specified=False,
            domain=domain,
            domain_specified=True,
            domain_initial_dot=False,
            path=path,
            path_specified=True,
            secure=False,
            expires=None,
            discard=False,
            comment=None,
            comment_url=None,
            rest=None
        )
if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    login = login()
    login.show()
    sys.exit(app.exec_())
